package com.dwy2002.appointment.interceptor;

import com.alibaba.fastjson2.JSON;
import com.dwy2002.common.utils.JwtUtil;
import com.dwy2002.common.utils.Utils;
import com.dwy2002.enums.Status;
import com.dwy2002.pojo.po.users.Users;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;

import static com.dwy2002.common.Result.fail;


/**
 * 从请求头中拿取并验证Token
 *
 * @author 杜伟毅
 * @since 2023/10/09
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class JwtValidateInterceptor implements HandlerInterceptor {
    private final JwtUtil jwtUtil;

    /**
     * 拦截器,用于从 Authorization 头中提取 JWT 并进行验证
     *
     * @param request  请求
     * @param response 响应
     * @param handler  处理程序
     * @return true：验证通过，false：验证不通过
     * @author 杜伟毅
     * @since 2024/11/2 0002 22:39
     */
    @Override
    public boolean preHandle(HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) throws IOException {
        // 从请求头中获取 Authorization 头
        String authorizationHeader = request.getHeader("Authorization");
        // 验证 Authorization 头是否存在,如果不存在，说明没有登录，返回错误信息
        if (Utils.isEmptyOrNull(authorizationHeader)) {
            //返回错误
            response.getWriter().write(JSON.toJSONString(fail(Status.UNAUTHORIZED, "token为空，请重新登录")));
            return false; // 拦截请求
        }
        // 验证 JWT
        jwtUtil.parseToken(authorizationHeader, Users.class);
        return true; // 验证通过，继续处理请求
    }
}
